/* Generating text output.
 * 
 * Copyright (c) 1993-2007 Leo Spiekman, Xaveer Leijtens
 *
 * This file is part of libMask.
 *
 * libMask is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * libMask is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with libMask.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "mask.h"

FILE *font;

char fontfile[100]="/opt/oed/lib/caps.plf";
double fontsize;

void setfont(char *name)
{
  strcpy(fontfile,name);
}

static void findletter(char ch)
{
  char lch;
  double x,y;
  int m;
  
  fscanf(font,"%c",&lch);
  while ((ch!=lch)&&(lch!='~')) {
    do {
      fscanf(font,"%lf %lf %d\n",&x,&y,&m);
    } while (m!=-1);
    fscanf(font,"%c",&lch);
  }
}

static void chout(char ch, double scalex, double scaley)
{
  double x, y, cx, cy, X[20], Y[20];
  const int up = 1, down = 0;
  int m, pen = up, i = 0;

  rewind(font);
  findletter(ch);
  push_cp();
  cx = 0.0;
  cy = 0.0;
  do {
    fscanf(font, "%lf %lf %d\n", &x, &y, &m);
    x *= fontsize / scalex;
    y *= fontsize / scaley;
    if (m == 1) {
      if (pen == up) {
	pen = down;
	i = 0;
	X[i] = cx;
	Y[i++] = cy;
      }
      X[i] = x;
      Y[i++] = y;
    } else {
      if (pen == down) {
	pen = up;
	if (mode & POLYGON) {
	  polylingo(X, Y, i, 0.07 * fontsize);
	} else {
	  npolyline(X, Y, i, 0.07 * fontsize);
	}
      }
    }
    cx = x;
    cy = y;
  } while (m != -1);
  pop_cp();
  move(cx, cy, 0.0, NOFLIP);
}

void textout(const char *t, double size)
{
  textout_stretch(t, size, 1);
}

void textout_stretch(const char *t, double size, double stretch)
{
  fontsize=size;
  if ((font=fopen(fontfile,"r")) == NULL) {
    fprintf(stderr, "Can't open fontfile '%s'.\n", fontfile);
    fprintf(stderr, "\t(You can use 'setfont()' to point to a valid fontfile.)\n");
    exit(1);
  }
  while(*t)
    chout(*t++, 8.0/stretch, 5.0);
  fclose(font);
}
